var express = require('express');
var router = express.Router();
var fields = 'id,snippet(title,description,publishedAt,thumbnails/default';
var uQuery = '';

function fetchWikiObject(query, freeObj){
  var wikiObject = freebase.description(query, {key:GoogleApiKey}, freeObj);
  return wikiObject;
};

function fetchYouTubeResults(query,tQuery, res){
    var params = {
        part: 'snippet',
        maxResults: 10,
        order: 'viewCount',
        q: tQuery,
        chart: 'mostPopular',
        auth: GoogleApiKey,
        regionCode: 'US'
//        fields: fields
    };

//    return function tubeSearch(){
        YouTube.search.list(params, function (err , data){
            console.log(err || data.items);
            function freeObjGrabber (description) {
//                if (typeof description === 'undefined')
//                {
//                    freebase.topic(query, {topic: '/common/topic', key:GoogleApiKey}, freeObjGrabber)
//                }
//                else {
                    console.log(description);
                    res.render('results', { title: 'Learn to Anything', topic: query, youtubeObjects: data.items, wikipediaObject: description });
//                }
            };
            freebase.description(query, {key:GoogleApiKey}, freeObjGrabber);

        });

//    }

};

//router.param('query', function(req, res, next, query){
//    uQuery = query.toString();
//    next();
//});

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Learn to Anything' });
});

//router.post('/results', function (req, res){
//    var oQuery = req.body.query;
//    var tQuery = 'how to '+oQuery + ' tutorial';
//    fetchYouTubeResults(oQuery, tQuery, res)
//
//});
router.get('/search/:query?', function (req, res){
    var oQuery = req.param('query');
    var tQuery = 'how to '+oQuery + ' tutorial -game -level -lvl -Minecraft -quest -xp -exp -gaming -enchanting -wow' ;
    fetchYouTubeResults(oQuery,tQuery, res);

    var wikiResults = 12;

//
//    var params = {
//        part: 'snippet',
//        maxResults: 5,
//        order: 'viewCount',
//        q: tQuery,
//        chart: 'mostPopular',
//        auth: GoogleApiKey
////        fields: fields
//    };
//    YouTube.search.list(params, function (err , data){
//        console.log(err || data.items);
////        youtubeResults = data.items;
//        res.writeData({youtubeObjects:data.items});
//
//    });


});

module.exports = router;
